package com.zjx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjx.reggie.common.R;
import com.zjx.reggie.dto.DishDto;
import com.zjx.reggie.entity.Category;
import com.zjx.reggie.entity.Dish;
import com.zjx.reggie.entity.DishFlavor;
import com.zjx.reggie.entity.Setmeal;
import com.zjx.reggie.service.CategoryService;
import com.zjx.reggie.service.DishService;
import com.zjx.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private DishService dishService;

    @Resource
    private SetmealService setmealService;


    @RequestMapping("/page")
    public R page(Integer page,Integer pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Category::getSort);
        categoryService.page(pageInfo,qw);
        return R.success(pageInfo);
    }

    @PutMapping()
    public R update(HttpServletRequest request, @RequestBody Category category){
        categoryService.updateById(category);
        return R.success("套餐修改成功！");
    }

    @PostMapping()
    public R save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功！");
    }

    @DeleteMapping()
    public R<String> delete(@RequestParam("ids")  String  id){
        categoryService.removeById(id);
        LambdaQueryWrapper<Setmeal> setmealQw = new LambdaQueryWrapper<>();
        setmealQw.eq(Setmeal::getCategoryId,id);
        LambdaQueryWrapper<Dish> dishQw = new LambdaQueryWrapper<>();
        dishQw.eq(Dish::getCategoryId,id);
        if(setmealService.count(setmealQw) > 0 || dishService.count(dishQw) > 0){
            return R.error("菜品中含有次分类！");
        }
        return R.success("删除成功！");
    }

    @GetMapping("/list")
    public R list(Category category) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(category.getType() != null, Category::getType, category.getType());
        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }


}
